package com.jinzhi.jzweb.strategy.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationResultsComDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.pojo.AsourVo;
import com.jinzhi.jzweb.pojo.CsourVo;
import com.jinzhi.jzweb.pojo.StuSignUpComNum2PoVo;
import com.jinzhi.jzweb.pojo.VtatisticsVo;
import com.jinzhi.jzweb.service.ExaminationBatchComSService;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.jzweb.strategy.BaseStrategy;
import com.jinzhi.jzweb.strategy.factory.SourConfig;
import com.jinzhi.jzweb.utils.DoubleUtil;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/*
 *  @author : JingChangTian
 *  @date   : 2023/6/3 14:20
 *  @description :  C赛场
 *
 */
@Component(value = "C")
public class ExaminationCSour extends BaseController implements BaseStrategy  {

    private final StuSignUpComService stuSignUpService;

    private final ExaminationResultsComService examinationResultsComService;

    private final ExaminationBatchComSService examinationBatchComSService;


    public ExaminationCSour(StuSignUpComService stuSignUpService,
                            ExaminationResultsComService examinationResultsComService, ExaminationBatchComSService examinationBatchComSService) {
        this.stuSignUpService = stuSignUpService;
        this.examinationResultsComService = examinationResultsComService;
        this.examinationBatchComSService = examinationBatchComSService;
    }

    /**
     * C赛场分数统计业务层
     * @param examinationAnswerSheetComDTO
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    @Override
    public Result<VtatisticsVo> list(ExaminationResultsComDO examinationAnswerSheetComDTO) throws NoSuchFieldException, IllegalAccessException {
        VtatisticsVo vtatisticsVo = new VtatisticsVo();
        Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();

        if(StringUtils.isNotBlank(examinationAnswerSheetComDTO.getUnitName())){
            wrapper.like("unit_name",examinationAnswerSheetComDTO.getUnitName());
        }
        // 查询列表数据
        Page<StuSignUpComDO> page = stuSignUpService.selectPage(getPage(StuSignUpComDO.class),
                wrapper.orderBy("id", false));
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExaminationResultsComDO obj = Optional.ofNullable(examinationResultsComService.findOneByKv("stu_sign_id",page.getRecords().get(i).getId())).orElse(new ExaminationResultsComDO());
            StuSignUpComDO stuSignUpComDO=page.getRecords().get(i);
            //裁判打分
            setScoingReferee(obj,stuSignUpComDO,"scoingc");
            double s1=((obj.getScoingc1()+obj.getScoingc2()+obj.getScoingc3()+obj.getScoingc4()+obj.getScoingc5())* SourConfig.network)/SourConfig.number;
            double s2=((obj.getScoingc1s()+obj.getScoingc2s()+obj.getScoingc3s()+obj.getScoingc4s()+obj.getScoingc5s())*SourConfig.teaching)/SourConfig.number;
            double s3=((obj.getScoingc1ls()+obj.getScoingc2ls()+obj.getScoingc3ls()+obj.getScoingc4ls()+obj.getScoingc5ls())*SourConfig.lecture)/SourConfig.number;
            BigDecimal bg = new BigDecimal(s1+s2+s3);
            Double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            obj.setScore(f1);
            list.add(obj);

        }
        DoubleSummaryStatistics collect = (DoubleSummaryStatistics) list.stream().collect(Collectors.summarizingDouble(ExaminationResultsComDO::getScore));
        vtatisticsVo.setMinScore(collect.getMin());
        vtatisticsVo.setMaxScore(collect.getMax());
        vtatisticsVo.setNumberPeople(Integer.parseInt(String.valueOf(collect.getCount())));
        page.setRecords(list);
        vtatisticsVo.setStuSignUpComDOs(page);
        return Result.ok(vtatisticsVo);
    }

    /**
     * 计算裁判打分
     * @param obj
     */
    public void setScoingReferee(ExaminationResultsComDO obj, StuSignUpComDO stuSignUpComDO, String scoing ) throws NoSuchFieldException, IllegalAccessException {
        for (int i = 1; i < SourConfig.number+1; i++) {
            Field field = obj.getClass().getDeclaredField(scoing+i);
            Field fields = obj.getClass().getDeclaredField(scoing+i+"s");
            Field fieldls = obj.getClass().getDeclaredField(scoing+i+"ls");
            //授权访问私有变量
            field.setAccessible(true);
            fields.setAccessible(true);
            fieldls.setAccessible(true);
            if(field.get(obj)==null){
                field.set(obj,0.0);
            }
            if(fields.get(obj)==null){
                fields.set(obj,0.0);
            }
            if(fieldls.get(obj)==null){
                fieldls.set(obj,0.0);
            }
            double s11=((Double) field.get(obj)*SourConfig.network);
            double f11 = DoubleUtil.douToTwo(s11);

            double s11s=((Double) fields.get(obj)*SourConfig.teaching);
            double f11s = DoubleUtil.douToTwo(s11s);

            double s11sl=((Double) fieldls.get(obj)*SourConfig.lecture);
            double f11sl = DoubleUtil.douToTwo(s11sl);
            String a=String.valueOf(f11)+"/"+(f11s)+"/"+(f11sl);
            switch (i){
                case 1:
                    obj.setScoreA(a);
                case 2:
                    obj.setScoreB(a);
                case 3:
                    obj.setScoreC(a);
                default:
                    break;
            }
        }
        obj.setNum2(stuSignUpComDO.getNum2());
        obj.setName(stuSignUpComDO.getName());
        obj.setUnitName(stuSignUpComDO.getUnitName());
        obj.setIdNumber(stuSignUpComDO.getIdNumber());
        obj.setTicketNumber(stuSignUpComDO.getTicketNumber());
        obj.setCandidateNumber(stuSignUpComDO.getCandidateNumber());
    }

    @Override
    public Page<StuSignUpComDO> getStuSignByCourt2(String id,Integer curr,Integer pageSize) {
        Page<StuSignUpComDO> page = new Page<>(
                Optional.of(curr).orElse(1),
                Optional.of(pageSize).orElse(10));
        //根据赛场id查询考生信息，理论赛场查询全部
        Page<StuSignUpComDO> sign = stuSignUpService.selectPage(page,new EntityWrapper<StuSignUpComDO>().
                eq(StringUtils.isNotBlank(id),"court2",id).
                isNotNull("court2"));
        sign.setRecords(sign.getRecords().stream().sorted(Comparator.comparing(StuSignUpComDO::getCourt2,Comparator.nullsLast(String::compareTo)).
                thenComparing(StuSignUpComDO::getRealityNm2,Comparator.nullsLast(String::compareTo))).
                collect(Collectors.toList()));

        //根据学生id查询成绩
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        sign.getRecords().forEach(a ->{
            examinationResultsComDO.setStuSignId(a.getId());
            a.setExaminationResultsComDO(examinationResultsComService.selectOne(examinationResultsComDO));
        });
        return sign;
    }

    @Override
    public String pageReturn() {
        return "jzweb/transcribe/recordpointsC";
    }


    @Override
    public String markReturn(Integer type) {
        if(type == 1){
            return "jzweb/transcribe/gradeC";
        }else if(type == 2){
            return "jzweb/transcribe/gradeCPo";
        }else if(type == 3){
            return "jzweb/transcribe/gradeCPos";
        }
        return null;
    }


    @Override
    public void downloadImportTemplate(HttpServletResponse response, String id) {
        List<CsourVo> csourVos = new ArrayList<>();
        //根据赛场id查询考生信息，理论赛场查询全部
        List<StuSignUpComDO> sign = stuSignUpService.selectList(new EntityWrapper<StuSignUpComDO>().
                eq(StringUtils.isNotBlank(id),"court2",id).
                isNotNull("court2"));
        sign.stream().sorted(Comparator.comparing(StuSignUpComDO::getCourt2,Comparator.nullsLast(String::compareTo)).
                thenComparing(StuSignUpComDO::getRealityNm2,Comparator.nullsLast(String::compareTo))).
                collect(Collectors.toList());

        //根据学生id查询成绩
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        sign.forEach(a ->{
            CsourVo csourVo = new CsourVo();
            examinationResultsComDO.setStuSignId(a.getId());
            ExaminationResultsComDO rcd = examinationResultsComService.selectOne(examinationResultsComDO);
            if(rcd!=null) {
                csourVo.setScoingc1(rcd.getScoingc1());
                csourVo.setScoingc2(rcd.getScoingc2());
                csourVo.setScoingc3(rcd.getScoingc3());
                csourVo.setRemarkC(rcd.getRemarkC());

                BigDecimal pjf = new BigDecimal( (rcd.getScoingc1() + rcd.getScoingc2() + rcd.getScoingc3()) /3);
                Double pjff = pjf.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                csourVo.setPjf(pjff);
            }
            csourVo.setName(examinationBatchComSService.selectById(a.getCourt2()).getName());
            csourVo.setRealityNm2(a.getRealityNm2());
            csourVos.add(csourVo);
        });
        String name = Optional.ofNullable(csourVos.get(0).getName()).orElse("");
        //导出操作
        EasyPoiUtil.exportExcel(csourVos, name+"赛场导出", name+"赛场导出", CsourVo.class, name+"赛场导出", response);
    }

}
